package com.mall.order.services;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.order.OrderQueryService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.converter.OrderConverter;
import com.mall.order.dal.entitys.*;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.OrderShippingMapper;
import com.mall.order.dto.*;
import com.mall.order.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

/**
 * 订单查询相关业务实现类
 * @author Javid Xi
 * @version 1.0
 * @since 2021/7/22
 */
@Slf4j
@Service
@Component
public class OrderQueryServiceImpl implements OrderQueryService {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderItemMapper orderItemMapper;
    @Autowired
    OrderConverter orderConverter;
    @Autowired
    OrderShippingMapper orderShippingMapper;

    /**
     * 查询用户订单总数
     * @param request 请求参数
     * @return OrderCountResponse
     */
    @Override
    public OrderCountResponse orderCount(OrderCountRequest request) {
        // 响应封装类
        OrderCountResponse response = new OrderCountResponse();

        try {
            Long userId = request.getUserId();
            Example orderExample = new Example(Order.class);
            orderExample.createCriteria().andEqualTo("userId", userId);
            int count = orderMapper.selectCountByExample(orderExample);
            // 封装响应
            response.setCount(count);
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            log.error("OrderQueryServiceImpl.orderCount Occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    /**
     * 查询用户所有订单
     * @param request 请求参数
     * @return OrderListResponse
     */
    @Override
    public OrderListResponse orderList(OrderListRequest request) {
        // 响应封装类
        OrderListResponse response = new OrderListResponse();
        response.setCode(OrderRetCode.SUCCESS.getCode());
        response.setMsg(OrderRetCode.SUCCESS.getMessage());

        try {
            // 参数校验
            request.requestCheck();
            // 分页
            PageHelper.startPage(request.getPage(), request.getSize());
            // 查询
            Example orderExample = new Example(Order.class);
            orderExample.createCriteria().andEqualTo("userId", request.getUserId());
            List<Order> orders = orderMapper.selectByExample(orderExample);

            if(CollectionUtils.isEmpty(orders)) { // 订单列表为空
                response.setTotal(0L);
                response.setDetailInfoList(new ArrayList<>());
                return response;
            }

            List<OrderDetailInfo> orderDetailInfos = new ArrayList<>();

            // 查询结果放进来
            PageInfo<Order> orderPageInfo = new PageInfo<>(orders);
            // 总的数据量
            long total = orderPageInfo.getTotal();
            response.setTotal(total);

            // 遍历订单列表 获取订单详情
            orders.forEach(order -> {
                OrderDetailInfo orderDetailInfo = getOrderDetailInfo(order);
                orderDetailInfos.add(orderDetailInfo);
            });

            // 封装响应
            response.setDetailInfoList(orderDetailInfos);

        } catch (Exception e) {
            log.error("OrderQueryServiceImpl.orderList Occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    /**
     * 获取订单详情
     * @param order 订单
     * @return OrderDetailInfo
     */
    private OrderDetailInfo getOrderDetailInfo(Order order) {
        // 转换
        OrderDetailInfo orderDetailInfo = orderConverter.order2detail(order);

        // 查询订单商品表
        Example orderItemExample = new Example(OrderItem.class);
        orderItemExample.createCriteria().andEqualTo("orderId", order.getOrderId());
        List<OrderItem> orderItems = orderItemMapper.selectByExample(orderItemExample);
        // 转换
        List<OrderItemDto> orderItemDtos = orderConverter.item2dto(orderItems);
        orderDetailInfo.setOrderItemDto(orderItemDtos);

        // 查询订单发货表
        OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(order.getOrderId());
        // 转换
        OrderShippingDto orderShippingDto = orderConverter.shipping2dto(orderShipping);
        orderDetailInfo.setOrderShippingDto(orderShippingDto);
        return orderDetailInfo;
    }

    /**
     * 查询订单明细
     * @param request 请求参数
     * @return OrderDetailResponse
     */
    @Override
    public OrderDetailResponse orderDetail(OrderDetailRequest request) {
        // 响应封装类
        OrderDetailResponse response = new OrderDetailResponse();
        try {
            // 参数校验
            request.requestCheck();

            // 查询订单
            Order order = orderMapper.selectByPrimaryKey(request.getOrderId());
            response = orderConverter.order2res(order);

            // 查询订单商品表
            Example orderItemExample = new Example(OrderItem.class);
            orderItemExample.createCriteria().andEqualTo("orderId", order.getOrderId());
            List<OrderItem> orderItems = orderItemMapper.selectByExample(orderItemExample);

            List<OrderItemDto> orderItemDtos = orderConverter.item2dto(orderItems);
            response.setOrderItemDto(orderItemDtos);

            // 查询订单发货表
            OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(order.getOrderId());
            OrderShippingDto orderShippingDto = orderConverter.shipping2dto(orderShipping);
            response.setOrderShippingDto(orderShippingDto);
            // 封装
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            log.error("OrderQueryServiceImpl.orderDetail occur Exception :" +e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    /**
     * 查询订单条目
     * @param request 请求参数
     * @return OrderItemResponse
     */
    @Override
    public OrderItemResponse orderItem(OrderItemRequest request) {
        return null;
    }
}
